package com.wjs.juc.Atmoic;

import com.sun.xml.internal.ws.streaming.MtomStreamWriter;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

class MyVar{
    public volatile Boolean isInit=Boolean.FALSE;

    AtomicReferenceFieldUpdater<MyVar,Boolean> fieldUpdater=AtomicReferenceFieldUpdater.newUpdater(MyVar.class,Boolean.class,"isInit");

    public void init(MyVar var) throws InterruptedException {
        if(fieldUpdater.compareAndSet(var,Boolean.FALSE,Boolean.TRUE)){
            System.out.println(Thread.currentThread().getName()+"正在初始化");
            TimeUnit.SECONDS.sleep(3);
            System.out.println(Thread.currentThread().getName()+"完成");
        }else {
            System.out.println("已经有任务在运行");
        }

    }


}
public class AtomicReferenceFieldUpdaterDemo {
    public static void main(String[] args) {
        MyVar myVar = new MyVar();
        for (int i = 0; i < 50; i++) {
            new Thread(()->{
                try {
                    myVar.init(myVar);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
